import React, { useEffect, useState } from 'react';
import { Form, Select, DatePicker, Button } from 'antd';
import { IGlobalControl } from '@/pages/Analysis/Board/components/Filters/types';
import { IDashboardItem } from '@/pages/SelfQuery/type';
import { FilterTypes } from '@/pages/Analysis/Board/components/Filters/constants';
import styles from './index.less';
import { IDistinctvaluePararm } from '@/pages/Analysis/type';
import { getdistinctvalue } from '@/services/analysis';
import { IResponse } from '@/models/connect';
import { SearchOutlined, ReloadOutlined } from '@ant-design/icons';

const { RangePicker } = DatePicker;
const { Option } = Select;

interface IProps {
  board: IDashboardItem
  onSave:(value:any)=>void
}


const FilterForm: React.FC<IProps> = (props) => {
  const { board,onSave } = props;
  const [controls, setControls] = useState<IGlobalControl[]>([]);
  const [formValues, setFormValues] = useState<{ key: string, values: any[] }[]>([]);
  const [queryMode, setQueryMode] = useState<number>(0);
  const [form] = Form.useForm();
  useEffect(() => {
    if (board && board.config) {
      const filters = JSON.parse(board.config);
      let filterList = [];
      if (filters && filters.filters) {
        filterList = filters.filters;
      }
      setControls(filterList);
      setQueryMode(Number(filters.queryMode));
    }
    else {
      setControls([]);
      setQueryMode(0);
    }
  }, [board.id,board.config]);

  useEffect(() => {
    setFormItemValues();
  }, [controls]);
  const setFormItemValues = async () => {
    let list: any = [];
    for (let i = 0; i < controls.length; i+=1) {
      const { relatedViews, type, key } = controls[i];
      if (![FilterTypes.InputText, FilterTypes.Select].includes(type)) {
        // eslint-disable-next-line no-continue
        continue;
      }
      const keys = Object.keys(relatedViews);
      if (keys && keys.length > 0) {
        const viewId = Number(keys[0]);
        // @ts-ignore
        const column = relatedViews[viewId].name;
        const params: IDistinctvaluePararm = { expired: 300, cache: false, columns: [column] };
        // eslint-disable-next-line no-await-in-loop
        const res: IResponse = await getdistinctvalue(viewId, params);
        if (res && res.header && res.header.code === 200) {
          const { payload } = res;
          const val = payload.map((p: any) => {
            return { label: String(p[column]), value: p[column] };
          });
          list = [...list, { key, values: val }];
        }

      }
    }
    setFormValues(list);

  };
  const onFormChange = () => {
    if(queryMode === 0){
      onSave(form.getFieldsValue())
    }
  };
  const selectRender = (control: IGlobalControl, mode?: 'multiple' | 'tags') => {
    const { type, key,dynamicDefaultValue } = control;
    const showSearch = type !== FilterTypes.Select;

    const formValue = formValues.find(v => v.key === key);
    console.log('control',control,formValue)

    const loading = !formValue;
    let values: any[] = [];
    if (formValue) {
      // eslint-disable-next-line prefer-destructuring
      values = formValue.values;
    }

    return (
      <Select
        allowClear
        // defaultValue={dynamicDefaultValue}
        mode={mode}
        loading={loading}
        showSearch={showSearch}
        style={{ width: 161 }}
        placeholder={showSearch ? '请输入' : '请选择'}
        filterOption={(input, option: any) =>
          option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
        }
        onChange={onFormChange}
      >
        {values.map(v => {
          return <Option value={v.value}>{v.label}</Option>;

        })}

      </Select>
    );
  };
  const formReset = () => {
    form.resetFields();
    onSave(form.getFieldsValue())
  };
  const onSearch = () => {
    onSave(form.getFieldsValue())
  };
  const formItem = (control: IGlobalControl) => {
    let { multiple, type, dateFormat } = control;
    // @ts-ignore
    dateFormat = dateFormat || 'YYYY-MM-DD'
    const mode = multiple ? 'multiple' : undefined;
    let formItem = null;
    if (type === FilterTypes.Select || type === FilterTypes.InputText) {
      formItem = selectRender(control, mode);
    } else if (type === FilterTypes.DateRange) {
      formItem = <RangePicker
        format={dateFormat}
        onChange={onFormChange}
      />;

    }
    return (
      <Form.Item
        name={control.key}
        label={control.name}
        className={styles.formItem}
      >
        {formItem}
      </Form.Item>
    );
  };
  if (!controls || !controls.length) {
    return null;
  }
  return (
    <div className={styles.filterForm}>

      <Form
        name='global_state'
        layout='inline'
        form={form}
      >
        {
          controls.map(c => {
            return formItem(c);
          })
        }
        {
          queryMode === 1 ?
            (
              <Form.Item style={{ marginTop: '16px' }}>
                <Button
                  type='primary'
                  onClick={onSearch}
                  style={{ marginRight: '8px' }}
                  icon={<SearchOutlined />}
                >
                  查询
                </Button>
                <Button
                  htmlType='button'
                  icon={<ReloadOutlined />}
                  onClick={formReset}
                >
                  重置
                </Button>
              </Form.Item>
            )
            : null
        }

      </Form>
    </div>
  );
};
export default FilterForm;
